package com.zhoujing.cinema.front.controller;

import com.zhoujing.cinema.constants.Constant;
import com.zhoujing.cinema.dao.UserDao;
import com.zhoujing.cinema.entity.User;
import com.zhoujing.cinema.service.UserService;
import com.zhoujing.cinema.utils.ResponseResult;
import com.zhoujing.cinema.utils.SendMsg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.UUID;

/**
 * Author:helloboy
 * Date:2020-01-30 18:37
 * Description:<描述>
 */
@Controller
@RequestMapping("/front/user")
public class UserController {
    @Autowired
    public UserService userService;
    @ResponseBody
    @RequestMapping("/loginByUsername")
    public ResponseResult loginByUsername(String username, String password, HttpServletResponse response){
        User user = userService.findUserByName(username);
        ResponseResult responseResult = new ResponseResult();
        if(user==null){
            responseResult.setStatus(Constant.RESPONSE_STATUS_FAILURE);
            responseResult.setData("");
            responseResult.setMessage("用户不存在");
        }else{
            if(!user.getPassword().equals(password)){
                responseResult.setStatus(Constant.RESPONSE_STATUS_FAILURE);
                responseResult.setData("");
                responseResult.setMessage("密码错误");
            }else{
                responseResult.setStatus(Constant.RESPONSE_STATUS_SUCCESS);
                responseResult.setData("");
                responseResult.setMessage("登录成功");
                Cookie cookie = new Cookie("userId",user.getId().toString());
                cookie.setMaxAge(60 * 60 * 24);
                cookie.setPath("/");
                response.addCookie(cookie);
            }
        }
        return responseResult;
    }
    @ResponseBody
    @RequestMapping("/getCheckCode")
    public ResponseResult getCheckCode(String phone, HttpServletRequest request){
        HttpSession session = request.getSession();
        session.removeAttribute("checkCode");
        ResponseResult result = new ResponseResult();
        String verificationCode = SendMsg.random(4);
        SendMsg.SendMsgs(phone,verificationCode);
        session.setAttribute("checkCode",verificationCode);
        //操作redis
        result.setStatus(Constant.RESPONSE_STATUS_SUCCESS);
        result.setMessage("发送成功");
        result.setData(verificationCode);
        return result;
    }
    @ResponseBody
    @RequestMapping("/loginByCheckCode")
    public ResponseResult loginByCheckCode(String phone,String checkCode,HttpServletRequest request,HttpServletResponse response){
        ResponseResult responseResult = new ResponseResult();
        User user = userService.findUserByName(phone);
        HttpSession session = request.getSession();
        if(user==null){
            responseResult.setStatus(Constant.RESPONSE_STATUS_FAILURE);
            responseResult.setData("");
            responseResult.setMessage("用户不存在");
        }else{
            String checkCodes = (String) session.getAttribute("checkCode");
            if(checkCodes.equals(checkCode)){
                responseResult.setStatus(Constant.RESPONSE_STATUS_SUCCESS);
                responseResult.setData("");
                responseResult.setMessage("登录成功");
                Cookie cookie = new Cookie("userId",user.getId().toString());
                cookie.setMaxAge(60 * 60 * 24);
                cookie.setPath("/");
                response.addCookie(cookie);
            }else{
                responseResult.setStatus(Constant.RESPONSE_STATUS_FAILURE);
                responseResult.setData("");
                responseResult.setMessage("验证码错误");
            }
        }
        return responseResult;
    }
    @ResponseBody
    @RequestMapping("/register")
    public ResponseResult register(String phone,String checkCode,String password,HttpServletRequest request,HttpServletResponse response){
        ResponseResult responseResult = new ResponseResult();
        User user = new User();
        user.setUsername(phone);
        user.setPassword(password);
        user.setIs_staff(0+"");
        user.setNickname("用户"+phone);
        user.setAvatar("http://127.0.0.1:8088/touxiang.png");
        HttpSession session = request.getSession();
        String checkCodes = (String) session.getAttribute("checkCode");
        if(checkCodes.equals(checkCode)){
            userService.addUser(user);
            Integer id = user.getId();
            responseResult.setStatus(Constant.RESPONSE_STATUS_SUCCESS);
            responseResult.setData("");
            responseResult.setMessage("登录成功");
            Cookie cookie = new Cookie("userId",id.toString());
            cookie.setMaxAge(60 * 60 * 24);
            cookie.setPath("/");
            response.addCookie(cookie);
        }else{
            responseResult.setStatus(Constant.RESPONSE_STATUS_FAILURE);
            responseResult.setData("");
            responseResult.setMessage("验证码错误");
        }
        return responseResult;
    }
    @PostMapping("/verifyUsername")
    @ResponseBody
    public boolean verifyUsername(@RequestParam(value = "phone",defaultValue = "") String name){
        return userService.verifyUsername(name);
    }
    @RequestMapping("/getUserInfo")
    @ResponseBody
    public ResponseResult getUserInfo(@CookieValue(value = "userId")String userId){
        ResponseResult responseResult = new ResponseResult();
        User user = userService.findUserById(Integer.parseInt(userId));
        responseResult.setStatus(Constant.RESPONSE_STATUS_SUCCESS);
        responseResult.setData(user);
        responseResult.setMessage("获取成功");
        return responseResult;
    }
    @RequestMapping("/changeUserInfo")
    @ResponseBody
    public ResponseResult changeUserInfo(@CookieValue(value = "userId")Integer userId,HttpServletRequest request) throws IOException {
        MultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        MultipartHttpServletRequest mreq = resolver.resolveMultipart(request);
        MultipartFile file = mreq.getFile("avatar");
        String fileName = file.getOriginalFilename();
        //上传图片
        String newFileName = UUID.randomUUID()+fileName.substring(fileName.lastIndexOf("."));
        String avatars = "http://127.0.0.1:8088/avatar/"+newFileName;
        String nickname = mreq.getParameter("nickname");
        User user = new User();
        user.setId(userId);
        user.setNickname(nickname);
        user.setAvatar(avatars);
        //file.transferTo(new File("D:\\images\\avatar"));
        try {
            File fileMkdir=new File("D:\\images\\avatar");

            if(!fileMkdir.exists()) {
                fileMkdir.mkdir();
            }
            //定义输出流 将文件保存在D盘    file.getOriginalFilename()为获得文件的名字
            FileOutputStream os = new FileOutputStream(fileMkdir.getPath()+"\\"+newFileName);
            InputStream in = file.getInputStream();
            int b = 0;
            while((b=in.read())!=-1){ //读取文件
                os.write(b);
            }
            os.flush(); //关闭流
            in.close();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        userService.modifyUserInfo(user);
        ResponseResult responseResult = new ResponseResult();
        responseResult.setStatus(Constant.RESPONSE_STATUS_SUCCESS);
        responseResult.setMessage("查询成功");
        return responseResult;
    }
}
